import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:ball_lion/base/base_controller.dart';
import 'package:ball_lion/module/record/channel_logic.dart';
import 'package:ball_lion/server/api/record_api.dart';
import 'package:ball_lion/entity/record/channel_entity.dart';
import 'package:ball_lion/module/record/channel_page.dart';

class DBMainLogic extends BaseController with GetTickerProviderStateMixin {
  late TabController zqController;
  List<ChannelEntity> _data = [];
  List<String> tabList = [];
  List<Widget> channelPages = [];
  List<ChannelEntity>? get data => _data;

  int _zqIndex = 1;
  int _headIndex = 0;
  int count = 0;
  bool isLoading = true;

  int get headIndex => _headIndex;
  int get zqIndex => _zqIndex;

  set zqIndex(int value) {
    _zqIndex = value;
    update();
  }

  set headIndex(int value) {
    _headIndex = value;
    update();
  }

  @override
  void onReady() {
    getData();
    super.onReady();
  }

  Future getData() async {
    _data = await RecordApi.myChannels(0) ?? [];
    try {
      tabList = _data.map((e) => e.channelName ?? "").toList();
      channelPages = List.generate(
          _data.length,
          (childIndex) => ChannelPage(
              data: _data[childIndex],
              type: 0,
              key: Key("zq${_data[childIndex].channelId}")));
    } catch (e) {
      Logger().d(e);
    }

    zqController =
        TabController(length: tabList.length, vsync: this, initialIndex: 0);
    zqController.addListener(() {
      zqIndex = zqController.index;
    });
    isLoading = false;
    update();
  }

  Future updateData(int index) async {
    var list = (await RecordApi.myChannels(index) ?? []);
    bool cheekLength = false;
    bool checkTab = false;
    if (_data.length != list.length) {
      cheekLength = true;
    } else {
      for (var i = 0; i < _data.length; i++) {
        if (_data[index].channelId != list[index].channelId) {
          checkTab = true;
          break;
        }
      }
    }
    if (cheekLength || checkTab) {
      var oldIndex = zqController.index;
      if (tabList[index].length - 1 < oldIndex) {
        oldIndex = tabList[index].length - 1;
      }
      zqController.dispose();
      zqController = TabController(
          length: tabList[index].length, vsync: this, initialIndex: oldIndex);
      zqIndex = oldIndex;
      zqController.addListener(() => zqIndex = zqController.index);
      update();
    }
  }

  void doRefresh() {
    Get.find<ChannelLogic>(tag: "${_data[zqIndex].channelId}0").doRefresh();
  }

  @override
  void getRefresh() {
    updateData(0);
    super.getRefresh();
  }

  toIndex(arguments) {}
}
